package com.leyou.trade.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.DEAD_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.ExchangeConstants.ORDER_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.DEAD_ORDER_QUEUE;
import static com.leyou.common.constants.MQConstants.QueueConstants.EVICT_ORDER_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.EVICT_ORDER_KEY;

/**
 * @author 付
 */
@Configuration
public class MqConfig {

    /**
     * 订单超时未支付的时间
     */
    private static final long ORDER_QUEUE_DELAY_TIME = 30000;

    /**
     * 普通交换机，用来接收订单信息
     * @return 交换机
     */
    @Bean
    public TopicExchange orderExchange() {
        return new TopicExchange(ORDER_EXCHANGE_NAME, true, false);
    }
    /**
     * 死信队列，用来接收消息，等待过期，转发给死信交换机
     * @return 队列
     */
    @Bean
    public Queue deadOrderQueue(){
        return QueueBuilder.durable(DEAD_ORDER_QUEUE)
                .withArgument("x-message-ttl", ORDER_QUEUE_DELAY_TIME)
                .withArgument("x-dead-letter-exchange", DEAD_EXCHANGE_NAME)
                .build();
    }

    /**
     * 普通交换机与死信队列的绑定
     * @return 绑定关系
     */
    @Bean
    public Binding deadOrderQueueBinding(){
        return BindingBuilder
                .bind(deadOrderQueue())
                .to(orderExchange())
                .with(EVICT_ORDER_KEY);
    }

    /**
     * 死信交换机，用来接收过期订单信息
     * @return 交换机
     */
    @Bean
    public TopicExchange deadExchange() {
        return new TopicExchange(DEAD_EXCHANGE_NAME, true, false);
    }
    /**
     * 任务队列，用来接收过期订单消息
     * @return 队列
     */
    @Bean
    public Queue evictOrderQueue(){
        return QueueBuilder.durable(EVICT_ORDER_QUEUE).build();
    }

    /**
     * 死信交换机到任务队列的绑定关系
     * @return 绑定
     */
    @Bean
    public Binding evictOrderQueueBinding(){
        return BindingBuilder
                .bind(evictOrderQueue())
                .to(deadExchange())
                .with(EVICT_ORDER_KEY);
    }

    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}